﻿#if NETSTANDARD
using CRL.Core.Remoting;
using CRL.DynamicWebApi;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
#endif
namespace CRL.DynamicWebApi.NetCore
{
#if NETSTANDARD
    public static class DynamicApiExtensions
    {
        static Action<AbsServer> _setupAction;
        static Assembly[] _assemblies;
        public static void AddDynamicApi(this IServiceCollection services, Action<AbsServer> setupAction, params Assembly[] assemblies)
        {
            _setupAction = setupAction;
            _assemblies = assemblies;
            services.AddSingleton<ServerCreater>();

            foreach (var assembyle in assemblies)
            {
                var types = assembyle.GetTypes();
                foreach (var type in types)
                {
                    if (type.IsSubclassOf(typeof(AbsService)) && !type.IsAbstract)
                    {
                        var implementedInterface = ServerCreater.GetImplementedInterface(type);
                        if (implementedInterface == null)
                        {
                            Console.WriteLine($"DynamicWebApi {type} 未实现接口，跳过注入");
                            continue;
                        }
                        //注册AbsService
                        services.AddTransient(implementedInterface, type);
                    }
                }
            }

        }
        public static void UseDynamicApi(this IApplicationBuilder app)
        {
            var serverCreater = app.ApplicationServices.GetService<ServerCreater>();
            var server = new ApiServer();
            serverCreater.SetServer(server, ServerType.DynamicWebApi);
            serverCreater.UseCoreInjection();
            _setupAction(server);
            serverCreater.RegisterAll(_assemblies);
            app.UseMiddleware<DynamicApiMiddleware>();
        }
    }
#endif
}
